/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-03-04
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-03-13
 * @Description: 
 */
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:chat_client/router/router.dart';

import 'notify_enum.dart';

class MobileNotify {
  /// 移动端本地通知

  static final _plugin = FlutterLocalNotificationsPlugin();

  /// 1.初始化
  static Future<void> initialize() async {
    await _plugin.initialize(
      InitializationSettings(
        android: AndroidInitializationSettings('@mipmap/ic_launcher'),
      ),
      // 前台点击处理
      onDidReceiveNotificationResponse: (notify) async {
        final payload = notify.payload;
        if (payload != null) {
          RouteManager.navigateWithPayload(payload);
        }
      },
    );

    // Android 13+ 动态请求权限
    final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>();
    await androidPlugin?.requestNotificationsPermission();
  }

  /// 2.显示通知
  static Future<void> show({
    required String title,
    required String content,
    NotificationType type = NotificationType.system,
    String? targetRoute, //// 路由路径
  }) async {
    // 根据类型生成渠道ID（允许自定义覆盖）
    final channel = _getChannelConfig(type);
    final details = AndroidNotificationDetails(
      channel.id,
      channel.name,
      icon: _getDefaultIcon(type),
      importance: Importance.max,
    );
    await _plugin.show(
      DateTime.now().millisecondsSinceEpoch.hashCode,
      title,
      content,
      NotificationDetails(android: details),
      payload: targetRoute ?? _getDefaultRoute(type),
    );
  }

// region 私有方法
  static ({String id, String name}) _getChannelConfig(
    NotificationType type,
  ) {
    // 默认渠道配置
    const defaultChannels = {
      NotificationType.system: ('system_channel', '系统通知'),
      NotificationType.friendRequest: ('friend_request', '好友申请'),
      NotificationType.chat: ('chat', '聊天消息'),
    };
    return (
      id: defaultChannels[type]!.$1,
      name: defaultChannels[type]!.$2,
    );
  }

  static String _getDefaultIcon(NotificationType type) {
    // 根据类型返回不同图标（需提前配置资源）
    switch (type) {
      case NotificationType.friendRequest:
        return 'ic_friend_request';
      case NotificationType.chat:
        // return '@mipmap/ic_chat';
        return 'ic_launcher';
      default:
        return 'ic_notification';
    }
  }

  static String _getDefaultRoute(NotificationType type) {
    // 根据类型返回不同的路由
    switch (type) {
      case NotificationType.friendRequest:
        return '/mobile-friend-request';
      default:
        return '/mobile-home';
    }
  }
}
